const router = require('koa-router')()
const fs = require('fs')
const path = require('path')
const koaBody = require('koa-body');

router.get('/', async (ctx, next) => {
  await ctx.render('index', {
    title: 'Hello Koa 2!'
  })
})

router.get('/string', async (ctx, next) => {
  ctx.body = 'koa2 string'
})

router.get('/json', async (ctx, next) => {
  ctx.body = {
    title: 'koa2 json'
  }
})

function mkdir(filePath) {
    fs.writeFileSync(filePath, '')
}

function saveFile(file) {
    // 文件夹不存在就创建
    let default_path = path.join(__dirname, '../public/upload/')
    !fs.existsSync(default_path) && fs.mkdirSync(default_path)
    // 创建可读流
    const reader = fs.createReadStream(file.path);
    console.log(222)
    let filePath = path.join(__dirname, '../public/upload/') + `/${file.name}`;
    // 创建可写流
    const upStream = fs.createWriteStream(filePath);
    // 可读流通过管道写入可写流
    reader.pipe(upStream);
    return `http://124.71.136.28:8080/imgfile/upload/${file.name}`
}

// 上传文件接口
router.post('/uploadfile', async (ctx, next) => {
    // 上传单个文件
    let file = ctx.request.files.file; // 获取上传文件
    // 支持多个文件
    !Array.isArray(file) && (file=[file])
    let returnArr = []
    file.forEach(item => {
        returnArr.push(saveFile(item))
    })
    return ctx.body = returnArr.length === 1 ? returnArr[0] : returnArr;
})

module.exports = router
